import os
import threading
import time
import win32gui
from PySide6.QtCore import Qt, QPoint
from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import  QWidget, QHBoxLayout, QVBoxLayout, QGridLayout
from qfluentwidgets import SingleDirectionScrollArea, SimpleCardWidget, CaptionLabel, LineEdit, ComboBox, PushButton, CheckBox
from core.screenshot import hwnd_title, get_all_hwnd, get_screenshot_image, get_mss_screenshot_image
from core.util import time_str, delete_file
from core.mh_util import find_mouse, is_popup
from core.maocr import maocr
from core.log import logger
import setting as c
import core.model_signin as u
from gui.common_gui import GUI_CARD

def background_task(obj):
    while True:
        # if obj.flag_start:
        #     logger.info(f"AutoTradeTrade task {obj.flag_start}")
        time.sleep(c.AUTO_INTERVAL)
        # if obj.flag_start:
        #     obj.detect()


class AutoTradeInfoCard(SimpleCardWidget):
    """ App information card """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.father = parent
        self.card = GUI_CARD.AUTOTRADE

        # 创建线程
        self.background_thread = threading.Thread(target=background_task, args=(self,), daemon=True)
        self.background_thread.start()
        
        self.alert_lb = CaptionLabel()
        self.alert_lb.setText(c.TIPS_SUBSCRIBE_ALERT)
        
        self.win_combo = ComboBox()
        self.update_win_combo()
        self.switch_btn = PushButton('Start')
        self.switch_btn.clicked.connect(self.onclick_switch)
        
        self.tips_label = CaptionLabel('')
        
        self.vBoxLayout = QVBoxLayout(self)
        self.vBoxLayout_alert= QVBoxLayout()
        self.hBoxLayout_win = QHBoxLayout()
        self.hBoxLayout_tips = QHBoxLayout()
        self.initLayout()

    def initLayout(self):
        
        self.vBoxLayout_alert.setSpacing(30)
        self.vBoxLayout_alert.setContentsMargins(34, 2, 24, 2)
        self.vBoxLayout_alert.addWidget(self.alert_lb)
        
        self.hBoxLayout_win.setSpacing(10)
        self.hBoxLayout_win.setContentsMargins(34, 2, 24, 2)
        self.hBoxLayout_win.addWidget(self.win_combo, 4)
        self.hBoxLayout_win.addWidget(self.switch_btn, 1)
        
        self.hBoxLayout_tips.setSpacing(10)
        self.hBoxLayout_tips.setContentsMargins(34, 2, 24, 2)
        self.hBoxLayout_tips.addWidget(self.tips_label)
        
        self.vBoxLayout.addLayout(self.vBoxLayout_alert)
        self.vBoxLayout.addLayout(self.hBoxLayout_win)
        self.vBoxLayout.addLayout(self.hBoxLayout_tips)

    def update_win_combo(self):
        self.win_combo.clear()
        hwnd_title.clear()
        win32gui.EnumWindows(get_all_hwnd, 0)
        for h, t in hwnd_title.items():
            # if t.startswith('梦幻西游 ONLINE'):
            if t.startswith('计算器'):
                self.win_combo.addItem(str(h)+":"+t)
                
    def getWinText(self):
        win_text = self.win_combo.currentText()
        if win_text == "":
            msg = "没有可用窗口"
            logger.warning(msg)
            self.setTips(msg) 
            self.update_win_combo()
            return None, False
        h = win_text.split(':')[0]
        t = win_text.split(':')[1]
        # logger.info(f"{h} {t}")
        
        if not win32gui.IsWindowEnabled(h):
            self.flag_start = False
            self.updateSwitch()
            self.setTips("无效窗口， 自动停止")
            self.update_win_combo()
            return None, False
    
        return (h, t), True
                
    def onclick_switch(self):
        
        if c.URL_QA == "":
            self.setTips("请先设置后台 ip 和 port")
            return
        
        if not self.flag_start and not u.signin_flag:
            msg = "仅登录用户可用"
            self.setTips(msg)
            logger.warning(msg) 
            return
        
        _, ok = self.getWinText()
        if not ok:
            self.flag_start = False  
            self.updateSwitch()
            self.setTips("窗口异常， 自动停止")
            return
            
        self.flag_start = not self.flag_start  
        self.updateSwitch()
        
    def updateSwitch(self):
        if self.flag_start:
            self.setTips("AutoTradeTrade task running...")
            self.switch_btn.setText(f"stop")
        else :
            self.setTips("AutoTradeTrade task stoped")
            self.switch_btn.setText(f"start")
            
    def setTips(self, tips):
        self.tips_label.setText(f"<font color='red'>{tips}</font>")
        
    def detect(self):
        
        if not u.signin_flag or u.signin_token == None:
            self.flag_start = False 
            self.updateSwitch()
            self.setTips("登录退出， 自动停止")
            return
        
        ht, ok = self.getWinText()
        if not ok:
            self.flag_start = False 
            self.updateSwitch()
            return
        h = ht[0]
        t = ht[1]
        
                    

    def altqwithcheck(self, img_hwnd, h):
        img_crop_1 = img_hwnd.crop(c.flag_tag_panel_cropbox)
        ts = time_str()
        file_img_1 = f"{c.shot_dir_path}/panel_1_{h}_{ts}.png"
        img_crop_1.save(file_img_1, 'PNG')
        logger.info(f'img_desktop save to -> {os.path.abspath(file_img_1)}')
        
        # mouse.click(Button.left, 1)
        time.sleep(0.01)
        
        img_hwnd = get_mss_screenshot_image(int(h))
        img_crop_2 = img_hwnd.crop(c.flag_tag_panel_cropbox)
        ts = time_str()
        file_img_2 = f"{c.shot_dir_path}/panel_2_{h}_{ts}.png"
        img_crop_2.save(file_img_2, 'PNG')
        logger.info(f'img_desktop save to -> {os.path.abspath(file_img_1)}')
        
        flag_popup = is_popup(file_img_1, file_img_2)
        logger.info(f"popup {h} {flag_popup}")
        return flag_popup
    
    def ctrltab(self):
        # mouse.click(Button.left, 1)
        time.sleep(0.01)
    
class AutoTradeInterface(SingleDirectionScrollArea):

    def __init__(self, parent=None):
        super().__init__(parent=None)
        self.main_window = parent
        self.view = QWidget(self)

        self.vBoxLayout = QVBoxLayout(self.view)
        self.autotradeCard = AutoTradeInfoCard(self)
        self.autotradeCard.setMaximumWidth(c.card_width)
        self.setWidget(self.view)
        self.setWidgetResizable(True)
        self.setObjectName('AutoTradeInterface')

        self.vBoxLayout.setSpacing(10)
        self.vBoxLayout.setContentsMargins(0, 0, 15, 0)
        self.vBoxLayout.addWidget(self.autotradeCard, 0, Qt.AlignTop)

        self.setStyleSheet("QScrollArea {border: none; background:transparent}")
        self.view.setStyleSheet('QWidget {background:transparent}')
        
    def show(self):
        logger.info("show AutoTradeInterface")
        